package com.yjf.ljr.activity;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yjf.ljr.R;
import com.yjf.ljr.adapter.CommonAdapter;
import com.yjf.ljr.adapter.InvestDetailAdapter;
import com.yjf.ljr.adapter.CommonAdapter.HandleCallBack;
import com.yjf.ljr.common.CommonData;
import com.yjf.ljr.dataclass.InvestDetailDataClass;
import com.yjf.ljr.dataclass.TransferDebtDataClass;
import com.yjf.ljr.dataclass.InvestDetailDataClass.ProjectInfo;
import com.yjf.ljr.dataclass.TransferDebtDataClass.TransfersListInfo;
import com.yjf.ljr.parser.RequestBuilder.RequestObject;
import com.yjf.ljr.util.AppUtil;
import com.yjf.ljr.view.XListView;
import com.yjf.ljr.view.XListView.IXListViewListener;

public class InvestListActivity extends IjActivity implements OnClickListener {

	public static final String BIZ_TYPE_CAREFREE = "public"; // 无忧宝

	/** 投资列表 **/
	private XListView mXlvCarefree;
	private XListView mXlvTransferDebt;
	private CommonAdapter mComTransferDebtAdapter;
	private InvestDetailAdapter mCarefreeAdapter;
	private List<ProjectInfo> mDataCarefree = new ArrayList<ProjectInfo>();
	private List<ProjectInfo> mDataMonth = new ArrayList<ProjectInfo>();

	private boolean mIsLoadingMore = false;
	private final int mPageSize = 10;
	private int mCurPageCarefree = 1;
	private int mCurPageMonthly = 1;

	private ViewPager mPager;// 页卡内容
	private List<View> mListViews; // Tab页面列表
	private ImageView mIvCursor;// 动画图片
	private int mOffset = 0;// 动画图片偏移量
	private int currIndex = 0;// 当前页卡编号
	private int mBmpW;// 动画图片宽度
	// private int mScreenW;
	private int mTabCurrentPosition = 0;
	private List<TransfersListInfo> mTransferDebt = new ArrayList<TransfersListInfo>();
	@ID("tvCarefree")
	private TextView mTvCarefree;
	@ID("tvMonthlyInterest")
	private TextView mTvMonthlyInterest;
	private DecimalFormat df = new DecimalFormat("######0.00");
	public static final String BIZ_TYPE_TRANSFERDEBT_INTEREST = "trasets"; //

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.homepg_invest_list);

		initControls();
		InitImageView();
		InitViewPager();

		showProgressDialog();
		new InvestTask(mPageSize, mCurPageCarefree, false, BIZ_TYPE_CAREFREE).execute();
	}

	/** 初始化控件 **/
	private void initControls() {
		findViewById(R.id.btn_title_left).setVisibility(View.GONE);
		setTitleStr("我要投资");
		mTvCarefree.setSelected(true);
		mTvCarefree.setOnClickListener(this);
		mTvMonthlyInterest.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tvCarefree:
			mPager.setCurrentItem(0);
			break;
		case R.id.tvMonthlyInterest:
			mPager.setCurrentItem(1);
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		// if (resultCode == RESULT_OK) {
		switch (requestCode) {
		case CommonData.REQUEST_CODE_LOGIN:
			showProgressDialog();
			if (mTabCurrentPosition == 0) { // 无忧宝
				mCurPageCarefree = 1;
				new InvestTask(mPageSize, mCurPageCarefree, false, BIZ_TYPE_CAREFREE).execute();
			} else if (mTabCurrentPosition == 1) { // 月息宝
				mCurPageMonthly = 1;
				new InvestTask(mPageSize, mCurPageMonthly, false, BIZ_TYPE_TRANSFERDEBT_INTEREST).execute();
			}
			break;
		}
		// }
		super.onActivityResult(requestCode, resultCode, intent);
	}

	/**
	 * 初始化动画
	 */
	private void InitImageView() {
		mIvCursor = (ImageView) findViewById(R.id.ivCursor);
		mBmpW = BitmapFactory.decodeResource(getResources(), R.drawable.delimiter_invest_list).getWidth();// 获取图片宽度
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenW = dm.widthPixels;// 获取分辨率宽度
		mOffset = (screenW / 2 - mBmpW) / 2;// 计算偏移量
		Matrix matrix = new Matrix();
		matrix.postTranslate(mOffset, 0);
		mIvCursor.setImageMatrix(matrix);// 设置动画初始位置
	}

	/**
	 * 初始化ViewPager
	 */
	@SuppressLint("ResourceAsColor")
	private void InitViewPager() {
		mPager = (ViewPager) findViewById(R.id.vPager);
		mListViews = new ArrayList<View>();
		LayoutInflater mInflater = getLayoutInflater();

		// 投资标
		View vCarefree = mInflater.inflate(R.layout.invest_list_carefree, null);
		mListViews.add(vCarefree);
		mXlvCarefree = (XListView) vCarefree.findViewById(R.id.xlvCarefree);
		mCarefreeAdapter = new InvestDetailAdapter(this, mDataCarefree);
		mXlvCarefree.setAdapter(mCarefreeAdapter);
		mXlvCarefree.setPullLoadEnable(true);
		mXlvCarefree.setPullRefreshEnable(true);
		mXlvCarefree.mFooterView.hide(); // 隐藏更多
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		mXlvCarefree.setRefreshTime(sdf.format(new Date()));
		mXlvCarefree.setXListViewListener(new IXListViewListener() {
			@Override
			public void onRefresh() {
				if (mIsLoadingMore) {
					return;
				}
				mCurPageCarefree = 1;
				mIsLoadingMore = true;
				new InvestTask(mPageSize, mCurPageCarefree, false, BIZ_TYPE_CAREFREE).execute();
			}

			@Override
			public void onLoadMore() {
				if (mIsLoadingMore) {
					return;
				}
				mIsLoadingMore = true;
				new InvestTask(mPageSize, ++mCurPageCarefree, true, BIZ_TYPE_CAREFREE).execute();
			}
		});
		// 转让标
		View vTransferDebt = mInflater.inflate(R.layout.invest_list_monthly_interest, null);
//		mListViews.add(vTransferDebt);
		mXlvTransferDebt = (XListView) vTransferDebt.findViewById(R.id.xlvMonthlyInterest);
		// mMonthAdapter = new InvestDetailAdapter(this, mTransferDebt);
		mComTransferDebtAdapter = new CommonAdapter(mContext, mTransferDebt, R.layout.item_transfer_debtadapter,
				ViewHolderTransferDebt.class, handleCallBackTransferDebt);
		mXlvTransferDebt.setAdapter(mComTransferDebtAdapter);
		mXlvTransferDebt.setPullLoadEnable(true);
		mXlvTransferDebt.setPullRefreshEnable(true);
		mXlvTransferDebt.mFooterView.hide(); // 隐藏更多
		mXlvTransferDebt.setRefreshTime(sdf.format(new Date()));
		mXlvTransferDebt.setXListViewListener(new IXListViewListener() {
			@Override
			public void onRefresh() {
				if (mIsLoadingMore) {
					return;
				}
				mCurPageMonthly = 1;
				mIsLoadingMore = true;
				new InvestTask(mPageSize, mCurPageMonthly, false, BIZ_TYPE_TRANSFERDEBT_INTEREST).execute();
			}

			@Override
			public void onLoadMore() {
				if (mIsLoadingMore) {
					return;
				}
				mIsLoadingMore = true;
				new InvestTask(mPageSize, ++mCurPageMonthly, true, BIZ_TYPE_TRANSFERDEBT_INTEREST).execute();
			}
		});

		mPager.setAdapter(new MyPagerAdapter(mListViews));
		mPager.setCurrentItem(0);
		mPager.setOnPageChangeListener(new MyOnPageChangeListener());
	}

	/*
	 * AsyncTask定义了三种泛型类型 Params，Progress和Result •doInBackground(Params… params)
	 * •publicProgress(Progress… progress) •onPostExecute(Result result)
	 */
	/** 首页投资数据获取 **/
	class InvestTask extends AsyncTask<Void, Void, String> {

		private int pageSize;
		private int curPage;
		private boolean isAdd = false;
		private String bizType;
		private InvestDetailDataClass dc = new InvestDetailDataClass();
		private TransferDebtDataClass dcT = new TransferDebtDataClass();

		public InvestTask(int pageSize, int curPage, boolean isAdd, String bizType) {
			super();
			this.pageSize = pageSize;
			this.curPage = curPage;
			this.isAdd = isAdd;
			this.bizType = bizType;
		}

		@Override
		protected String doInBackground(Void... params) {
			RequestObject reqObj = new RequestObject();
			if (bizType.equals("trasets")) {
				reqObj.method = "transfersProjectList";
				reqObj.map.put("pageSize", pageSize);
				reqObj.map.put("pageNumber", curPage);
				reqObj.map.put("status", "3");
				return requestDataAndGetErrorMsg(reqObj, dcT);
			} else {
				reqObj.method = "appProjectList";
				reqObj.map.put("pageSize", pageSize);
				reqObj.map.put("pageNumber", curPage);
				// reqObj.map.put("bizType", bizType);
				reqObj.map.put("status", 1);
				return requestDataAndGetErrorMsg(reqObj, dc);
			}

		}

		@Override
		protected void onPostExecute(String result) {
			if (!TextUtils.isEmpty(result)) {
				showToast(result);
			} else {
				if (BIZ_TYPE_CAREFREE.equals(bizType)) { // 无忧宝
					if (!isAdd) {
						mDataCarefree.clear();
					}
					if (dc.projectList != null && dc.projectList.size() > 0) {
						mDataCarefree.addAll(dc.projectList);
						mCarefreeAdapter.notifyDataSetChanged();

						if (mDataCarefree.size() <= (dc.totalPage - 1) * pageSize) {
							mXlvCarefree.mFooterView.show();
						} else {
							mXlvCarefree.mFooterView.hide();
						}
					}
				} else { //
					if (!isAdd) {
						mTransferDebt.clear();
					}
					if (dcT.list != null && dcT.list.size() > 0) {
						mTransferDebt.addAll(dcT.list);
						mComTransferDebtAdapter.notifyDataSetChanged();

						if (mTransferDebt.size() <= (dcT.totalPage - 1) * pageSize) {
							mXlvTransferDebt.mFooterView.show();
						} else {
							mXlvTransferDebt.mFooterView.hide();
						}
					} else {
						showToast("暂无数据");
					}
				}
			}
			mXlvCarefree.stopRefresh();
			mXlvCarefree.stopLoadMore();
			mXlvTransferDebt.stopRefresh();
			mXlvTransferDebt.stopLoadMore();
			dismissProgressDialog();
			mIsLoadingMore = false;
		}
	}

	/**
	 * ViewPager适配器
	 */
	public class MyPagerAdapter extends PagerAdapter {
		public List<View> mListViews;

		public MyPagerAdapter(List<View> mListViews) {
			this.mListViews = mListViews;
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView(mListViews.get(arg1));
		}

		@Override
		public void finishUpdate(View arg0) {
		}

		@Override
		public int getCount() {
			return mListViews.size();
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(mListViews.get(arg1), 0);
			return mListViews.get(arg1);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == (arg1);
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}
	}

	/**
	 * 头标点击监听
	 */
	public class MyOnClickListener implements View.OnClickListener {
		private int index = 0;

		public MyOnClickListener(int i) {
			index = i;
			setCurrentPosition(i);
		}

		@Override
		public void onClick(View v) {
			if (mPager.getCurrentItem() != index) {
				mPager.setCurrentItem(index);
			}
		}
	};

	/**
	 * 页卡切换监听
	 */
	public class MyOnPageChangeListener implements OnPageChangeListener {

		int one = mOffset * 2 + mBmpW;// 页卡1 -> 页卡2 偏移量
		int two = one * 2;// 页卡1 -> 页卡3 偏移量

		@Override
		public void onPageSelected(int arg0) {

			Animation animation = null;
			animation = new TranslateAnimation(one * currIndex, one * arg0, 0, 0);
			currIndex = arg0;
			animation.setFillAfter(true);// True：图片停在动画结束位置
			animation.setDuration(300);
			mIvCursor.startAnimation(animation);
			if (arg0 == 1 && mTransferDebt.size() == 0) {
				showProgressDialog();
				new InvestTask(mPageSize, mCurPageMonthly, false, BIZ_TYPE_TRANSFERDEBT_INTEREST).execute();
			}
			mTabCurrentPosition = arg0;
			setCurrentPosition(arg0);
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		return false;
	}

	private void setCurrentPosition(int position) {
		if (position == 0) {
			mTvCarefree.setSelected(true);
			mTvMonthlyInterest.setSelected(false);
		} else if (position == 1) {
			mTvCarefree.setSelected(false);
			mTvMonthlyInterest.setSelected(true);
		}
	}

	private HandleCallBack handleCallBackTransferDebt = new HandleCallBack() {

		@SuppressWarnings("deprecation")
		@SuppressLint("NewApi")
		@Override
		public void handle(int position, View convertView, ViewGroup parent, Object holder, Object item) {
			// TODO Auto-generated method stub
			TransfersListInfo transfersListInfo = new TransfersListInfo();
			final ViewHolderTransferDebt viewHolder = (ViewHolderTransferDebt) holder;
			transfersListInfo = (TransfersListInfo) item;
			viewHolder.tvInvestTrastTitle.setText(transfersListInfo.tradeName);// 债券转让标题
			viewHolder.tvTransferPrice.setText(AppUtil.changeMoneyCompany(transfersListInfo.amount));// 转让价格
			viewHolder.tvResidualTerm.setText(transfersListInfo.leftTime + "天");// 剩余期限

			viewHolder.tvExpectedReturn.setText(AppUtil.changeMoneyCompany(transfersListInfo.interestAmount));// 预计收益

			final String tradeName = transfersListInfo.tradeName;// 交易名称
			double douProfitRate;
			String realProfitRate;
			if (!TextUtils.isEmpty(transfersListInfo.realProfitRate)) {
				douProfitRate = Double.parseDouble(transfersListInfo.realProfitRate) * 100;
				realProfitRate = df.format(douProfitRate);// 年化收益率
			} else {
				realProfitRate = "无";// 年化收益率
			}
			viewHolder.tvAnnualInterestRate.setText(realProfitRate);// 年利化率
			final String amount = transfersListInfo.amount;// 转让金额
			final String leftTime = transfersListInfo.leftTime;// 贷款期限
			final String tradeExpireDate = transfersListInfo.tradeExpireDate;// 借款到期日期
			final String transferDate = transfersListInfo.transferExpireDate;// 转让时间
			final String status = transfersListInfo.status;// 转让状态
			final String InterestAmount = transfersListInfo.interestAmount;// 预计收益
			final String transferExpireDate = transfersListInfo.transferExpireDate.toString();
			final String tradeId = transfersListInfo.tradeId.toString();// 关联交易id
			final String tradeTransferId = transfersListInfo.tradeTransferId;// 转让id
			final String investAmount = transfersListInfo.investAmount;// 转让id
			final String tradeDetailId = transfersListInfo.tradeDetailId;// 转让id
			final String applyUserId = transfersListInfo.applyUserId;// 申请转让用户ID

			if (!TextUtils.isEmpty(transfersListInfo.tradeExpireDate)
					&& (transfersListInfo.tradeExpireDate.length() >= 10)) {
				viewHolder.tvExpirationTime.setText(transfersListInfo.tradeExpireDate.subSequence(0, 10));// 到期时间
			} else if (!TextUtils.isEmpty(transfersListInfo.tradeExpireDate)) {
				viewHolder.tvExpirationTime.setText(transfersListInfo.tradeExpireDate);// 到期时间
			}
			viewHolder.tvInvestTraseStatus.setText(transfersListInfo.status);// 状态
			if ("转让成功".equals(transfersListInfo.status)) {
				viewHolder.llInvestTrastBg.setBackgroundColor(Color.parseColor("#cccccc"));
				viewHolder.tvInvestTraseStatus.setText("转让完成");// 状态
				viewHolder.ivitemtype.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.yzr));
			} else {
				viewHolder.ivitemtype.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.zrz));
				viewHolder.llInvestTrastBg.setBackgroundColor(Color.parseColor("#39A1EA"));// b43924
			}

			if (!TextUtils.isEmpty(transfersListInfo.transferExpireDate)
					&& (transfersListInfo.transferExpireDate.length() >= 10)) {
				viewHolder.tvCloseTime.setText("转让截止时间：" + transfersListInfo.transferExpireDate.subSequence(0, 10));// 截止时间
			} else if (!TextUtils.isEmpty(transfersListInfo.transferExpireDate)) {
				viewHolder.tvCloseTime.setText("转让截止时间：" + transfersListInfo.transferExpireDate);// 截止时间
			}

			convertView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub

					Intent intent = new Intent(InvestListActivity.this, DebtorDeatailActivity.class);
					intent.putExtra("tradeName", tradeName);// 交易名称
					intent.putExtra("profitRate", viewHolder.tvAnnualInterestRate.getText().toString());// 年化收益率
					intent.putExtra("amount", amount);// 转让金额
					intent.putExtra("timeLimit", leftTime);// 贷款期限
					intent.putExtra("tradeExpireDate", tradeExpireDate);// 借款到期日期
					intent.putExtra("transferExpireDate", transferExpireDate);// 转让截止时间
					intent.putExtra("status", status);// 转让状态
					intent.putExtra("InterestAmount", AppUtil.changeMoneyCompany(InterestAmount));// 预计收益
					intent.putExtra("tradeId", tradeId);// 关联交易id
					intent.putExtra("tradeTransferId", tradeTransferId);// 转让id
					intent.putExtra("investAmount", investAmount);// 投资金额
					intent.putExtra("tradeDetailId", tradeDetailId);// 关联投资id
					intent.putExtra("applyUserId", applyUserId);// 申请转让用户ID
					startActivity(intent);
				}
			});
		}
	};

	public static class ViewHolderTransferDebt {

		TextView tvInvestTrastTitle;// 债券转让标题
		TextView tvTransferPrice;// 转让价格
		TextView tvResidualTerm;// 剩余期限
		TextView tvAnnualInterestRate;// 年利化率
		TextView tvExpectedReturn;// 预计收益
		TextView tvExpirationTime;// 到期时间
		TextView tvInvestTraseStatus;// 状态
		TextView tvCloseTime;// 截止时间
		LinearLayout llInvestTrastBg;//
		ImageView ivitemtype;// 标类型
	}
}
